// 预订支付
import { directPay } from "@src/api/booking";
import {
  balancePay,
  getWxPrepay,
  queryOrderStatus,
} from "@src/api/reservation";
import { getAccount, getAccountPayConfig } from "@src/api/member";
import md5 from "@src/common/md5";

module.exports = Behavior({
  data: {
    accountInfo: {},
    accountPayRule: {},
    maxPayLatency: 0,
    queryTimes: 1,
  },
  ready: function () {
    this.$pay = this.selectComponent("#pay");
    this.getAccountInfo();
  },
  methods: {
    getAccountInfo() {
      getAccount().then((res) => {
        if (res.code === 0) {
          this.setData({ accountInfo: res.data });
        } else {
          this.setData({ accountInfo: null });
        }
      });
      getAccountPayConfig().then((res) => {
        this.setData({ accountPayRule: res.data });
      });
    },
    toPay(options) {
      let { orderNo, payFee, maxPayLatency } = options;
      this.setData({
        maxPayLatency,
      });
      return new Promise((resolve, reject) => {
        this.setData({ payResolve: resolve, payReject: reject });
        // if (payFee === 0) {
        //   // 0 元支付
        //   this.startDirectPay(orderNo);
        // }
        let accountPayRule = this.data.accountPayRule;
        let accountInfo = this.data.accountInfo;
        let account = {
          balance: 0,
          canUseDiscount: false,
          requirePassword: false,
        };
        let payChannels = this.data.payChannels;
        if (accountInfo) {
          account = {
            balance:
              (accountInfo.balance || 0) +
              (accountInfo.giftBalance || 0) -
              (accountInfo.lockedBalance || 0) -
              (accountInfo.lockedGiftBalance || 0),
            canUseDiscount: accountPayRule.canUseDiscount,
            requirePassword: accountPayRule.canSkipPwd
              ? payFee > accountPayRule.skipPwdAmount
              : true,
          };
        } else {
          if (payChannels.indexOf("balance") !== -1) {
            payChannels.splice(payChannels.indexOf("balance"), 1);
          }
        }
        this.$pay.openPay({
          payChannels: this.data.payChannels,
          account: account,
          payFee: payFee,
          maxPayLatency: maxPayLatency,
          confirm: (payChannel, password) => {
            if (payChannel === "wx") {
              this.startWxPay(orderNo);
            } else {
              this.startBalancePay(orderNo, password);
            }
          },
          cancel: () => {
            // 用户取消支付, 跳转到订单详情页
            this._payFail();
          },
        });
      });
    },
    startDirectPay(orderNo) {
      this.$pay.showLoading();
      directPay({ orderNo })
        .then((res) => {
          this.$pay.hideLoading();
          if (res.code === 0) {
            this.startPollOrderStatus(orderNo);
          } else {
            // 直接回调支付失败,
            this._payFail();
          }
        })
        .catch(() => {
          this._payFail();
        });
    },
    startWxPay(orderNo) {
      getWxPrepay({ orderNo, shopId: this.data.shopInfo.shopInfoResp.shopId })
        .then((res) => {
          if (res.code === 0) {
            this.$pay.hideLoading();
            wx.requestPayment({
              timeStamp: res.data.payTimestamp + "",
              nonceStr: res.data.payNonceStr,
              package: res.data.payPackage,
              signType: res.data.paySignType,
              paySign: res.data.paySignature,
              success: () => {
                this.$pay.showLoading();
                this.startPollOrderStatus(orderNo);
              },
              fail: () => {
                // 用户取消支付, 允许用户重新发起支付
                if (this.$pay.data.visible) {
                  this.$pay.hideLoading();
                  wx.showToast({
                    title: "用户取消支付",
                    icon: "none",
                    duration: 1500,
                  });
                } else {
                  wx.showToast({
                    title: "用户取消支付",
                    icon: "none",
                    duration: 1500,
                  });
                  this._payFail(res.msg);
                }
              },
            });
          } else {
            // 直接回调支付失败,
            this._payFail(res.msg);
          }
        })
        .catch((error) => {
          this._payFail(error.data, error.data.msg);
        });
    },
    startBalancePay(orderNo, password) {
      if (password) {
        password = password; //md5(password) 注释md5
      }
      return balancePay({ orderNo, password })
        .then((res) => {
          if (res.code === 0) {
            this.startPollOrderStatus(orderNo);
          } else {
            // 刷新余额
            this.getAccountInfo();
            // 隐藏支付loading, 允许用户重新发起支付
            this.$pay.resetPassword();
            this.$pay.hideLoading();
            wx.showToast({ title: res.msg, icon: "none", duration: 4000 });
          }
        })
        .catch(() => {
          this._payFail();
        });
    },
    startPollOrderStatus(orderNo) {
      this.setData({ queryTimes: 1 });
      this.innerQuery(orderNo);
    },
    innerQuery(orderNo) {
      if (this.data.queryTimes > 5) {
        this._payFail("查询支付状态超时");
        return;
      }
      queryOrderStatus({ orderNo }).then((res) => {
        if (res.code !== 0) {
          this.setData({ queryTimes: this.data.queryTimes + 1 });
          this.innerQuery(orderNo);
          return;
        }
        let payStatus = res.data;
        // let payStatus = "WAITING";
        if (payStatus === "PAYED") {
          this._paySuccess();
        } else if (payStatus === "WAITING") {
          setTimeout(() => {
            this.setData({ queryTimes: this.data.queryTimes + 1 });
            this.innerQuery(orderNo);
          }, 1000);
        } else if (payStatus === "CANCEL") {
          this._payFail({ code: -2, msg: "支付失败,请重试" });
        } else if (payStatus === "UNDERWAY") {
          this._payFail("支付失败,请重试");
        }
      });
    },
    _paySuccess() {
      this.$pay.hideLoading();
      this.$pay.close();
      this.data.payResolve();
    },
    _payFail(reason, msg) {
      if (msg) {
        wx.showToast({ title: msg, icon: "none", duration: 4000 });
      }
      this.$pay.hideLoading();
      this.$pay.close();
      this.data.payReject({ reason: reason });
    },
  },
});
